package cn.itcast.bos.web.action.take_delivery;

import java.io.File;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import cn.itcast.bos.domain.take_delivery.Promotion;
import cn.itcast.bos.service.take_delivery.PromotionService;
import cn.itcast.bos.web.action.common.BaseAction;





@SuppressWarnings("serial")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
@Namespace("/")
public class PromotionAction extends BaseAction<Promotion>{
    //属性驱动接收文件上传项
	private File titleImgFile;  //与 
	private String titleImgFileFileName;//图片的名字
    
	
	public void setTitleImgFile(File titleImgFile) {
		this.titleImgFile = titleImgFile;
	}

	public void setTitleImgFileFileName(String titleImgFileFileName) {
		this.titleImgFileFileName = titleImgFileFileName;
	}

	//属性注入service
	@Autowired
	private PromotionService promotionService;
	
	
//	添加功能 save 方法
	@Action(value="promotion_save",results={@Result(name="success",type="redirect",
			location="./pages/take_delivery/promotion.html")})
	public String save() throws Exception{
		//文件保存路径
		String savePath = ServletActionContext.getServletContext().getRealPath("/upload");
		//响应给前台页面的相对路径
		String saveUrl = ServletActionContext.getRequest().getContextPath()+"/upload";
		
		//生成随机图片名
		UUID uuid = UUID.randomUUID(); //生成随机UUID
		//截取图片名称中的扩展名比如.jpg 注意文件的扩展名和文件类型是不一样的
		String imgType = titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));
	    String randomImgName = uuid + imgType;
	          
	   //保存图片
	    File destFile = new File(savePath+"/"+randomImgName);
	    System.out.println("图片保存在"+destFile.getAbsolutePath());
	    FileUtils.copyFile(titleImgFile,destFile );
	   
	    
	    model.setTitleImg(saveUrl+"/"+randomImgName);
	    promotionService.save(model);
		return SUCCESS;
	}
	
	
	//分页查询 显示宣传活动列表
	@Action(value="promotion_pageQuery",results={@Result(type="json",name="success")})
	public String pageQuery(){
		Pageable pageable = new PageRequest(page -1, rows);
		System.out.println(pageable);
		Page<Promotion> pageDate = promotionService.findPageDate(pageable);
		pushPageDataToValueStack(pageDate);
		return SUCCESS;
	}
	
	
}
